package cn.iocoder.yudao.module.trade.controller.app.order;

import cn.iocoder.yudao.framework.common.enums.trade.TradeOrderStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.pay.api.notify.dto.PayOrderNotifyReqDTO;
import cn.iocoder.yudao.module.pay.api.order.dto.PayOrderCreateReqDTO;
import cn.iocoder.yudao.module.trade.controller.app.order.vo.*;
import cn.iocoder.yudao.module.trade.convert.order.TradeOrderConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.framework.order.config.TradeOrderProperties;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderUpdateService;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 App - 交易订单")
@RestController
@RequestMapping("/trade/order")
@Validated
@Slf4j
public class AppTradeOrderController {

    @Resource
    private TradeOrderUpdateService tradeOrderUpdateService;
    @Resource
    private TradeOrderQueryService tradeOrderQueryService;
    @Resource
    private TradeOrderProperties tradeOrderProperties;

    @PostMapping("/create")
    @Operation(summary = "创建订单")
    public CommonResult<AppTradeOrderCreateRespVO> createOrder(@Valid @RequestBody AppTradeOrderOrderCreateReqVO createReqVO) {
        TradeOrderDO order = tradeOrderUpdateService.createOrder(getLoginUserId(), createReqVO);
        return success(new AppTradeOrderCreateRespVO().setNo(order.getOrderNo()).setPayOrderId(order.getPayOrderId()));
    }

    /**
     * // 由 pay-module 支付服务，进行回调，可见 PayNotifyJob
     * 全款单支付完成后回调
     * 锁价单-> 结算 -> 支付结算单 -> 支付完成 回调
     * 旧料兑换 -> 结算 -> 支付结算单 -> 支付完成 回调
     */
    @PostMapping("/update-paid")
    @Operation(summary = "订单完成")
    @PermitAll
    public CommonResult<Boolean> updateOrderPaid(@RequestBody PayOrderNotifyReqDTO notifyReqDTO) {
        tradeOrderUpdateService.updateOrderPaid(notifyReqDTO);
        return success(true);
    }

    @PostMapping("/create-pay-order")
    @Operation(summary = "订单生成支付单")
    @PermitAll
    public CommonResult<AppTradeOrderCreateRespVO> createPayOrder(@RequestParam String orderNo, @RequestParam BigDecimal price, @RequestParam Integer payType) {
        return success(tradeOrderUpdateService.createPayOrder(orderNo, price, payType));
    }

    @PostMapping("/settle-info")
    @Operation(summary = "获得结算信息")
    public CommonResult<PayOrderCreateReqDTO> settlementOrder(@Valid @RequestBody AppTradeOrderSettleReqVO reqVo) {
        return success(tradeOrderUpdateService.getSettleInfo(reqVo.getOrderNo(),
                reqVo.getOrderWeight(), reqVo.getIsViolate()));
    }


    /**
     * 锁价单 -> 结算 -> 支付结算单
     * 旧料兑换 -> 结算 -> 支付结算单
     */
    @PostMapping("/settle")
    @Operation(summary = "订单生成支付结算单")
    @PermitAll
    public CommonResult<AppTradeOrderCreateRespVO> createPaySettled(@Valid @RequestBody AppTradeOrderSettleReqVO reqVo) {
        return success(tradeOrderUpdateService.createPaySettled(reqVo.getOrderNo(), reqVo.getOrderWeight(), reqVo.getAutoPay(),
                reqVo.getIsStore(), reqVo.getIsViolate(), null, reqVo.getCollectInfoId(), reqVo.getBankInfoId()));
    }

    @PostMapping("/confirm-check")
    @Operation(summary = "确认核验信息")
    public CommonResult<AppTradeOrderDetailRespVO> confirmCheck(@Valid @RequestBody AppTradeOrderSettleReqVO reqVo) {
        return success(tradeOrderUpdateService.confirmCheck(reqVo));
    }

    @GetMapping("/get-detail")
    @Operation(summary = "获得交易订单")
    @Parameters({
            @Parameter(name = "id", description = "交易订单编号"),
            @Parameter(name = "sync", description = "是否同步支付状态", example = "true")
    })
    public CommonResult<AppTradeOrderDetailRespVO> getOrderDetail(@RequestParam("id") String orderNo,
                                                                  @RequestParam(value = "sync", required = false) Boolean sync) {
        return success(tradeOrderQueryService.getOrderDetial(orderNo));
    }

    @PutMapping("/delivery")
    @Operation(summary = "提交快递")
    public CommonResult<Boolean> deliveryOrder(@RequestBody AppTradeOrderDeliveryReqVO deliveryReqVO) {
        tradeOrderUpdateService.deliveryOrder(deliveryReqVO);
        return success(true);
    }

    @GetMapping("/get-express-track-list")
    @Operation(summary = "获得交易订单的物流轨迹")
    @Parameter(name = "id", description = "交易订单编号")
    public CommonResult<List<AppOrderExpressTrackRespDTO>> getOrderExpressTrackList(@RequestParam("id") Long id) {
        return success(TradeOrderConvert.INSTANCE.convertList02(
                tradeOrderQueryService.getExpressTrackList(id, getLoginUserId())));
    }

    @GetMapping("/page")
    @Operation(summary = "获得交易订单分页")
    public CommonResult<PageResult<AppTradeOrderPageRespVO>> getOrderPage(AppTradeOrderPageReqVO reqVO) {
        // 查询订单
        PageResult<TradeOrderDO> pageResult = tradeOrderQueryService.getOrderPage(getLoginUserId(), reqVO);
        return success(TradeOrderConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/get-count")
    @Operation(summary = "获得交易订单数量")
    public CommonResult<Map<String, Long>> getOrderCount() {
        Map<String, Long> orderCount = Maps.newLinkedHashMapWithExpectedSize(5);
        // 全部
        orderCount.put("allCount", tradeOrderQueryService.getOrderCount(getLoginUserId(), null, null));
        // 待付款（未支付）
        orderCount.put("unpaidCount", tradeOrderQueryService.getOrderCount(getLoginUserId(),
                TradeOrderStatusEnum.UNPAID.getStatus(), null));
        // 待发货
        orderCount.put("undeliveredCount", tradeOrderQueryService.getOrderCount(getLoginUserId(),
                TradeOrderStatusEnum.PREPARE_DONE.getStatus(), null));
        // 待收货
        orderCount.put("deliveredCount", tradeOrderQueryService.getOrderCount(getLoginUserId(),
                TradeOrderStatusEnum.DELIVERED.getStatus(), null));
        // 待评价
        orderCount.put("uncommentedCount", tradeOrderQueryService.getOrderCount(getLoginUserId(),
                TradeOrderStatusEnum.COMPLETED.getStatus(), false));
        return success(orderCount);
    }

    @PutMapping("/receive")
    @Operation(summary = "确认交易订单收货")
    @Parameter(name = "id", description = "交易订单编号")
    public CommonResult<Boolean> receiveOrder(@RequestParam("orderNo") String orderNo) {
        tradeOrderUpdateService.receiveOrderByMember(getLoginUserId(), orderNo);
        return success(true);
    }

    @DeleteMapping("/cancel")
    @Operation(summary = "取消交易订单")
    @Parameter(name = "id", description = "交易订单编号")
    public CommonResult<Boolean> cancelOrder(@RequestParam("id") Long id) {
        tradeOrderUpdateService.cancelOrderByMember(getLoginUserId(), id);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除交易订单")
    @Parameter(name = "id", description = "交易订单编号")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") String id) {
        tradeOrderUpdateService.deleteOrder(getLoginUserId(), id);
        return success(true);
    }

}
